import { memo, forwardRef, useState, useImperativeHandle, ForwardRefRenderFunction, useMemo, useCallback } from 'react'
import { Modal, Form, message } from 'antd'
import { HsAdminForm } from '@hs-admin/base-components'
import { projectStageType } from '@/utils/type'
import { HsAdminSelectUsers } from '@/components/global'
import { addProjectList, editProjectList, getProjectInfor } from '@/api/developCenter/project'
import { getProjectSourceType } from '@hs-admin/api'

interface Props {
  finish: () => void
}
const ProjectEdit: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref: any) => {
  const { finish } = props
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [form] = Form.useForm()
  const [formValues, setformValues] = useState<any>({})
  const [modalType, setmodalType] = useState('新增')
  const [ownerUserOptions, setownerUserOptions] = useState<any[]>([])
  const [memberUserOptions, setmemberUserOptions] = useState<any[]>([])

  const formItemOptions = useMemo(
    () => [
      {
        label: '项目名称',
        name: 'name',
        required: true,
        component: 'Input',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '当前阶段',
        name: 'stage',
        required: true,
        component: 'Select',
        componentProps: {
          options: projectStageType()
        },
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '项目类型',
        name: 'kind',
        required: true,
        component: 'Select',
        componentProps: {
          options: getProjectSourceType()
        },
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '预计/合同金额',
        name: 'expected_amount',
        component: 'InputNumber',
        FormItemColProps: {
          span: 12
        },
        suffix: () => <div className="flex-none ml-2">万元</div>
      },
      {
        label: '项目负责人',
        name: 'owner_user_id',
        slot: 'owner_user_id',
        FormItemColProps: {
          span: 12
        }
      },
      {
        label: '项目团队成员',
        name: 'member_user_ids',
        slot: 'member_user_ids',
        FormItemColProps: {
          span: 12
        }
      }
    ],
    []
  )

  const handleOk = async () => {
    form
      .validateFields()
      .then(async (values) => {
        const params: any = {
          id: formValues.id,
          ...values,
          expected_amount: values.expected_amount * 10000,
          owner_user_id: values.owner_user_id || null,
          member_user_ids: values.member_user_ids || null
        }
        let callFn = addProjectList
        let text = '新增成功'
        if (params.id) {
          callFn = editProjectList
          text = '编辑成功'
        }
        await callFn(params)
        message.success(text)
        finish()
        handleCancel()
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  }
  const handleCancel = () => {
    setmodalType('新增')
    form.resetFields()
    setformValues({})
    setIsModalOpen(false)
  }
  const showModal = useCallback(
    (item: any) => {
      if (item) {
        getProjectInfor({ id: item.id }).then((res) => {
          form.setFieldsValue({
            ...res,
            expected_amount: res.expected_amount / 10000,
            member_user_ids: res.members.map((ele: { id: string }) => ele.id)
          })
          setformValues(res)
          setmodalType('编辑')
          setownerUserOptions([
            {
              label: res.owner_user?.name,
              value: res.owner_user?.id
            }
          ])
          setmemberUserOptions(
            res.members.map((ele: { name: string; id: string }) => ({
              ...ele,
              label: ele.name,
              value: ele.id
            }))
          )
        })
      }
      setIsModalOpen(true)
    },
    [form]
  )

  useImperativeHandle(
    ref,
    () => {
      return {
        showModal
      }
    },
    [showModal]
  )

  return (
    <Modal title={`${modalType}项目`} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={800}>
      <HsAdminForm form={form} formItemOptions={formItemOptions} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
        <div slot="owner_user_id">
          <HsAdminSelectUsers placeholder="请选择项目负责人" options={ownerUserOptions}></HsAdminSelectUsers>
        </div>
        <div slot="member_user_ids">
          <HsAdminSelectUsers placeholder="请选择项目团队成员" options={memberUserOptions} mode="multiple"></HsAdminSelectUsers>
        </div>
      </HsAdminForm>
    </Modal>
  )
}

export default memo(forwardRef(ProjectEdit))
